package question.abFile2C;

import java.io.*;

/**
 * 将a,b文件中的单词整合到c文件中
 * Created by yangliwei on 2018/3/12.
 */
public class Main {
    //这里没有使用volatile因为volatile 只有在状态真正独立于程序内其他内容时才能使用 volatile  一般作为状态标识
    private final static StringBuffer gsb = new StringBuffer();

    public static void main(String[] args) {
        String dirPath = Main.class.getResource("").getPath();
        String aFilePath = "a.txt";
        String bFilePath = "b.txt";
        String cFilePath = "c.txt";
        long start = System.currentTimeMillis();
        readWords2SB(dirPath+File.separator+aFilePath,dirPath+File.separator+bFilePath);
        writeWords2C(dirPath+ File.separator+cFilePath);
        long end = System.currentTimeMillis();
        System.out.println("consume: "+(end-start));
    }

    //将gsb中的单词读入c.txt中
    private static void writeWords2C(String filePath) {
        File file = new File(filePath);
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            writer.write(gsb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //将a.txt和b.txt文件读入gsb中
    private static void readWords2SB(String aFilePath, String bFilePath) {
        File aFile = new File(aFilePath);
        File bFile = new File(bFilePath);
        Reader aReader = null;
        Reader bReader = null;
        try {
            aReader = new FileReader(aFile);
            bReader = new FileReader(bFile);
            //这里需要完善，选择全部单词加载过来，直接把文件全部加载过来很low，
            // 需要分段加载，但是分段加载又会出现最后一个单词是否分割的问题,
            //因为一次就读完了，所以也没有必要线程同步了，贼尴尬
            char[] ca = new char[(int) aFile.length()];
            char[] cb = new char[(int) bFile.length()];
            aReader.read(ca);
            bReader.read(cb);
            String sa = new String(ca);
            String sb = new String(cb);
            String[] ssa = sa.split(" |\n");
            String[] ssb = sb.split(" |\n");
            int i = 0;
            for (i = 0; i < ssa.length; i++) {
                gsb.append(ssa[i] + "----");
                if (i < ssb.length)
                    gsb.append(ssb[i] + "\n");
            }
            for (; i < ssb.length; i++) {
                gsb.append(ssb[i] + "\n");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (aReader != null)
                    aReader.close();
                if (bReader != null)
                    bReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
